﻿/// <reference path="../../../plugins/layui/plugins/eleTree/eleTree.js" />
/// <reference path="../../../plugins/layui/plugins/eleTree/eleTree.js" />
$(function () {
    //2.初始化页面
    var oPageInit = new PageInit();
    oPageInit.Init();
    oPageInit.LoadRoleEmployee();
});

var PageInit = function () {
    var oInit = new Object();
    var postdata = {};

    var table, form, layer, tree, util;
    var active;
    var tableId = 'tb_list';

    //初始化页面上面的按钮事件
    oInit.Init = function () {
        layui.use(['table', 'tree', 'util'], function () {
            table = layui.table
          , tree = layui.tree
          , util = layui.util
          , form = layui.form
          , layer = layui.layer;
            oInit.loadData();
        })
    }

    //初始化Table,加载数据
    oInit.loadData = function () {
        //方法级渲染
        table.render({
            elem: '#' + tableId
            , id: tableId
        , loading: true
            //, skin: 'line' //line （行边框风格） row （列边框风格） nob （无边框风格）
        , even: false //开启隔行背景
        , size: 'lg' //小尺寸的表格
        , toolbar: '#toolbar'
        , defaultToolbar: ['']  //工具栏右侧的图标按钮
        , url: Root + 'FZUser/GetSysUser'
        , cols: [[
        { checkbox: true, fixed: true }, { type: 'numbers', title: '序号' }
        , {
            field: 'account',
            title: '用户账号'
        }, {
            field: 'roleName',
            title: '角色名称'
        }, {
            field: 'employeeName',
            title: '员工姓名'
        }, {
            field: 'employeeCode',
            title: '员工编号'
        }, {
            field: 'updatetime',
            title: '更新时间',
            width: 110,
            templet: function (row) {
                return row.updatetime == null ? '' : changeDateFormat(row.updatetime)
            }
        }, {
            title: '重置密码',
            width: 100,
            align: 'center',
            templet: function (row) {
                return '<i data-index="' + row.LAY_TABLE_INDEX + '" data-id="' + row.id + '" class="layui-icon layui-icon-key tableResetPwd" style="cursor: pointer;font-size: 22px;"></i>';
            }
        }, {
            field: 'isLocked',
            title: '锁定状态',
            align: 'center',
            unresize: true,
            templet: function (row) {
                //return row.isLocked == null || row.isLocked == 0 ? "否" : "是";
                var btnHtml = '';
                btnHtml += '<input type="checkbox" name="lock" value="' + row.id + '" title="锁定" lay-filter="tableIsLock" class="layui-btn layui-btn-danger" ' + (row.isLocked == null || row.isLocked == 0 ? '' : 'checked') + '>';

                if (row.errorTimes >= 10) {
                    btnHtml += '&nbsp;&nbsp;&nbsp;&nbsp;<i data-index="' + row.LAY_TABLE_INDEX + '" data-id="' + row.id + '" class="layui-icon layui-icon-password tableErrorTimes" title="密码错误次数达到最大值,点此解锁" style="cursor: pointer;font-size: 22px;"></i>';
                }
                return btnHtml;
            }
        }, {
            field: 'updatetime',
            title: '创建时间',
            width: 110,
            templet: function (row) {
                return row.updatetime == null ? '' : changeDateFormat(row.updatetime)
            }
        }
        , {
            fixed: 'right', title: '操作', toolbar: '#tableBar', width: 120,
        }
        ]]
        , page: true
        , limit: 10
            //, cellMinWidth: 80
        , height: 'full-300'
        });

        var $ = layui.$;
        active = {
            reload: function () {
                var txt_search = $('#txt_search');
                var temp = {
                    SearchText: txt_search.val(),
                };

                //执行重载
                table.reload(tableId, {
                    method: 'post',
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                  , where: temp
                }, 'data');
            }
        };

        $('#formSearch .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //监听工具条增删改按钮
        zpActive.tableTool(table, layer, form, null, null, null, null, null, oInit.Delete, null);

        //监听提交按钮
        form.on('submit(save)', function (data) {
            var rs = oInit.Save(data.field);    //保存数据
            if (rs) {
                active.reload();    //重新加载table数据
                layer.closeAll();   //关闭弹出层
            }
            return false;   //true刷新当前页面
        });

        form.on('select(selRoleId)', function (data) {
            //var val = data.value;
            var text = data.elem[data.elem.selectedIndex].text;
            $('#txtRoleName').val(text);
        });

        form.on('select(selEmployeeId)', function (data) {
            //var val = data.value;
            var text = data.elem[data.elem.selectedIndex].text;
            $('#txtEmployeeName').val(text);
        });

        //监听重置密码操作
        $(document).on('click', '.tableResetPwd', function (obj) {
            //layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
            //var tableList = table.cache[tableId];
            //var row;
            //tableList.forEach(item => {
            //    if (item.LAY_TABLE_INDEX == $(obj.currentTarget).attr('data-index')) {
            //        row = item;
            //    }
            //});
            var id = $(obj.currentTarget).attr('data-id');
            layer.confirm('确定重置密码为 123456 么？', function () {
                oInit.Locked(id, true, "1");
            });
        });

        //监听锁定操作
        form.on('checkbox(tableIsLock)', function (obj) {
            //layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
            oInit.Locked(this.value, obj.elem.checked, "2");
        });

        //监听密码次数过多解锁操作
        $(document).on('click', '.tableErrorTimes', function (obj) {
            //layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
            //var id = $(obj.currentTarget).attr('data-id');
            var id = $(obj.currentTarget).data('id');
            //var errorTimes = $(obj.currentTarget).attr('data-errorTimes');
            oInit.Locked(id, true, "3");
        });

        oInit.LoadRoleEmployee();
    }


    //1锁定/0解锁
    oInit.Locked = function (id, isChecked, operate) {
        var row = {
            id: id,
            isLocked: isChecked ? 1 : 0,
        }
        $.ajax({
            type: "post",
            url: Root + 'FZUser/SaveSysUser',
            data: { dto: row, operate: operate },
            success: function (result) {
                if (result.SubmitResult) {
                    if (operate == "1") {
                        dialog.success('密码重置成功，新密码为：123456');
                    }
                    active.reload();
                } else {
                    //table.update(tableId, [{ id: id, isLocked: isChecked }]);
                    var oldData = table.cache[tableId]; //获取表格当前的缓存数据 #datatab为table的id
                    oldData.forEach(function (item, i) {
                        if (item && item.id == id) {
                            item.isLocked = isChecked ? 0 : 1; //未成功还原状态
                        }
                    });
                    table.reload({ data: oldData });//Table为已定义的数据表格引用

                    dialog.danger('操作失败！Error Message:' + result.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () {

            }
        });
    }

    //保存-新增
    oInit.Save = function (formdata) {
        //var dto = decodeURIComponent(formdata, true);   //处理中文,后台需要解码
        var result = false;
        //静态添加节点
        $.ajax({
            type: "post",
            url: Root + 'FZUser/SaveSysUser',
            async: false,
            data: { dto: formdata },
            success: function (data) {
                if (data.SubmitResult) {
                    result = true;
                } else {
                    dialog.danger('操作失败！Error Message:' + data.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () {

            }
        });
        return result;
    }

    //删除
    oInit.Delete = function (arr_obj) {
        for (var i = 0; i < arr_obj.length; i++) {
            if (arr_obj[i].roleId == 1) {
                dialog.warning('超级管理员不能删除！');
                return;
            }
        }

        $.ajax({
            type: "post",
            url: Root + 'FZUser/DeleteSysUser',
            data: { dto: arr_obj },
            success: function (data) {
                if (data.SubmitResult) {
                    dialog.success('删除成功');
                    active.reload();
                } else {
                    dialog.danger('操作失败！Error Message:' + data.Message);
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () { }
        });
    }

    //加载下拉菜单数据
    oInit.LoadRoleEmployee = function () {
        //加载角色信息
        var roleId = '#selRoleId';
        $.ajax({
            type: "post",
            async: false,
            url: Root + 'FZRole/GetAllSysRole',
            success: function (data) {
                if (data.msg && data.msg != '') {
                    dialog.danger(data.msg);
                } else {
                    var select = $(roleId);
                    select.empty();
                    $.each(data.data, function (i, item) {
                        select.append('<option value="' + item.id + '" ' + (item.id == 1 ? 'disabled' : '') + '>' + item.name + '</option>');
                    });
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () { }
        });

        //加载员工信息
        var employeeId = '#selEmployeeId';
        var temp = { isPaging: false };
        $.ajax({
            type: "post",
            async: false,
            url: Root + 'FZEmployee/GetBaseEmployee',
            data: { dto: temp },
            success: function (data) {
                if (data.msg && data.msg != '') {
                    dialog.danger(data.msg);
                } else {
                    var select = $(employeeId);
                    select.empty();
                    $.each(data.data, function (i, item) {
                        select.append('<option value="' + item.id + '">' + item.name + '</option>');
                    });
                }
            },
            error: function () {
                dialog.danger('操作失败！请重试或者联系管理员');
            },
            complete: function () { }
        });
    }
    return oInit;
}